// pages/moreCharge/index.js

const util = require('../../utils/util.js');
const tool = require('../../utils/tool.js');

const api = require('../../config/api.js');
const user = require('../../utils/user.js');
const selectStore = require('../../utils/selectStore.js');

//获取应用实例
const app = getApp();


Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    keyWord: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getLinks();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.getLinks();
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  inputChange: function (e) {

    let keyWord = e.detail.value;
    this.setData({
      keyWord: keyWord,
    })
    this.getLinks();

  },
  //首页链接
  getLinks() {
    try {
      let that = this;
      let indexId = selectStore.getSelectIndex();
      console.log(indexId);
      util.request(api.chargesList, {
        "keyWord": that.data.keyWord,
      }, 'GET').then(function (res) {
        if (res.errno === 0) {
          let data = res.data;

          data.forEach(item => {
            item.selected = item.id == indexId ? true : false;
          });
          if (!indexId) {
            data[0].selected = true;
          }

          that.setData({
            list: data,
          })

        }

      }).catch(err => {

      });
    } catch (err) {
      console.error(err);
    }

  },

  selectItem(e) {
    user.getUserInfoServer().then(res => {
      const index = e.currentTarget.dataset.index;
      const id = e.currentTarget.dataset.id;
      selectStore.setSelectIndex(id);
      let list = this.data.list.map(item => {
        // 当前点击项：选中状态切换，其他项全部取消选中
        return {
          ...item,
          selected: item.id === id ? !item.selected : false
        }
      });

      this.setData({
        list
      });

      let currentItem = this.data.list[index];

      console.log(currentItem);
      //url
      if (!currentItem.isCalculate) {
        let url = currentItem.url + "?chargeId=" + id + "&token=" + user.getLoginToken();
        console.log(url);

        util.parseWebViewUrl(url);
      } else {
        this.goCalculateDetai(currentItem.id);
      }




    }).catch(err => {
      util.showErrorToast(err);
    })

  },
  /**计算公式 */
  goCalculateDetai(chargeId) {
    wx.navigateTo({
      url: `/pages/calculateCharge/index?chargeId=${chargeId}`,
    })
  }

})